package com.web.system.action;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.opensymphony.xwork2.ModelDriven;
import com.util.BaseActionUtil;
import com.util.JsonUtil;
import com.web.system.po.RolePo;
import com.web.system.po.TreeMenuPo;
import com.web.system.po.UserPo;
import com.web.system.service.RoleService;
import com.web.system.service.TreeMenuService;

@Controller @Scope("prototype") 
@ParentPackage(value = "struts-default")
@Namespace(value = "/")
@Action(value = "roleAction",results={
		@Result(name="input",type="redirect", location="/login.jsp")
})
public class RoleAction extends BaseActionUtil implements ModelDriven<RolePo>{

	/**
	 * 
	 */
	private static final long serialVersionUID = 2754864511859193200L;
	
	@Resource
	private RoleService roleService;
	@Resource
	private TreeMenuService treeMenuService;
	
	private RolePo role;
	public RolePo getModel() {
		// TODO Auto-generated method stub
		role = new RolePo();
		return role;
	}
	

	/**
	 * 显示切换角色列表
	 * @return
	 * @throws Exception
	 */
	public String getUserRole() throws Exception{
		UserPo userPo = (UserPo) session.getAttribute("user");
		List<RolePo> rolePos = userPo.getRoleBeans();
		for (RolePo rolePo : rolePos) {
			rolePo.setTreeMenuPos(null);
			rolePo.setUserBeans(null);
		}
		out.print(JsonUtil.objectToStr(rolePos));
		out.flush();
		out.close();
		return NONE;
	}
	
	/**
	 * 切换角色
	 * @return
	 * @throws Exception
	 */
	public String changeRole() throws Exception {
		String roleId = request.getParameter("changeRole");
		session.setAttribute("roleId", Integer.parseInt(roleId));
		out.print("1");
		out.flush();
		out.close();
		return NONE;
	}
	
	/**
	 * 角色是否存在
	 * @return
	 * @throws Exception
	 */
	public String isExistRole() throws Exception{
		
		String name = request.getParameter("name");
		//System.out.println(name);
		out.print(roleService.isExistRole(name) ? "0" : "1");
		out.flush();
		out.close();
		return NONE;
	}
	
	/**
	 * 查询所有的用户角色,供用户选择
	 * @return
	 * @throws Exception
	 */
	public String getAllRole() throws Exception {
		List<RolePo> rolePos = roleService.getAllRole();
		for (int i = 0; i < rolePos.size(); i++) {
			rolePos.get(i).setTreeMenuPos(null);
			rolePos.get(i).setUserBeans(null);
		}
		out.print(JsonUtil.objectToStr(rolePos));
		out.flush();
		out.close();
		return NONE;
	}
	
	/**
	 * 分页显示数据
	 * @return
	 * @throws Exception
	 */
	public String getRoleList() throws Exception {
		
		//分页部分
		int page = Integer.parseInt(request.getParameter("page"));
		int pageSize = Integer.parseInt(request.getParameter("rows"));
		int first = pageSize * (page - 1);
		String order = request.getParameter("order");
		String sort = request.getParameter("sort");
		
		//搜索部分
		String sql = "";
		String column = request.getParameter("column");
		String value = request.getParameter("value");
		if(value != null && !"".equals(value) && !"null".equals(value)){
			sql += " and role." ;
			/*jsp那边都是column+Search*/
			sql += column.substring(0,column.length() - 6);
			sql += " like '%" + value + "%'";
		}
		//组合最终sql语句
		StringBuffer queryStringBuffer = new StringBuffer();
		queryStringBuffer.append("FROM RolePo as role where 1=1 and isdelete = 0 ");
		queryStringBuffer.append(sql);
		queryStringBuffer.append(" ORDER BY  ");
		queryStringBuffer.append(sort);
		queryStringBuffer.append(" ");
		queryStringBuffer.append(order);
        List<RolePo> roles = roleService.getRoleList(queryStringBuffer.toString(), first, pageSize);
        int total = roleService.getTotal(sql);
        Map<String, Object> mapJson = new HashMap<String, Object>();
        mapJson.put("total", total);
        mapJson.put("rows", roles);
        out.print(JsonUtil.objectToStr(mapJson, new String[]{"treeMenuPos","userBeans"}));
        out.flush();
        out.close();
		return NONE;
	}

	/**
	 * 增加角色
	 * @return
	 * @throws Exception
	 */
	public String addRole() throws Exception {
		
		String authIds = request.getParameter("authIds");
		String[] menuIds = authIds.split(",");
		Set<TreeMenuPo> treeMenuPos = new HashSet<TreeMenuPo>();
		for (String menuId : menuIds) {
			TreeMenuPo treeMenuPo = treeMenuService.getTreeMenuPoByMenuId(menuId);
			if(treeMenuService != null){
				treeMenuPos.add(treeMenuPo);
			}
		}
		role.setTreeMenuPos(treeMenuPos);
		role.setIsDelete(0);
		out.print(roleService.saveOrUpdateRoleAndMenu(role) ? "1" : "0");
		out.flush();
		out.close();
		return NONE;
	}
	
	
	public String getRoleByRoleId() throws Exception {
		String roleId = request.getParameter("roleId");
		RolePo rolePo = roleService.getRoleByRoleId(Integer.parseInt(roleId));
		Map<String, Object> map = new HashMap<String, Object>();
		Set<TreeMenuPo> menuPos = rolePo.getTreeMenuPos();
		if(menuPos != null && menuPos.size() > 0){
			String[] menuIds = new String[menuPos.size()];
			int i = 0;
			for (TreeMenuPo treeMenuPo : menuPos) {
				menuIds[i++] = treeMenuPo.getId();
			}
			map.put("menuIds", menuIds);
		}
		map.put("role", rolePo);
		out.print(JsonUtil.objectToStr(map, new String[]{"treeMenuPos","userBeans"}));
		out.flush();
		out.close();
		return NONE;
	}
	
	/**
	 * 更新角色
	 * @return
	 * @throws Exception
	 */
	public String updateRole() throws Exception {
		
		RolePo rolePo = roleService.getRoleByRoleId(role.getRoleId());
		String authIds = request.getParameter("authIds");
		String[] menuIds = authIds.split(",");
		Set<TreeMenuPo> treeMenuPos = new HashSet<TreeMenuPo>();
		for (String menuId : menuIds) {
			TreeMenuPo treeMenuPo = treeMenuService.getTreeMenuPoByMenuId(menuId);
			if(treeMenuPo != null){
				treeMenuPos.add(treeMenuPo);
			}
		}
		rolePo.setTreeMenuPos(treeMenuPos);
		out.print(roleService.saveOrUpdateRoleAndMenu(rolePo) ? "1" : "0");
		out.flush();
		out.close();
		return NONE;
	}
	
	/**
	 * 删除角色
	 * @return
	 * @throws Exception
	 */
	public String deleteRole() throws Exception {
		
		String roleIds = request.getParameter("roleIds");
		UserPo userPo = (UserPo) session.getAttribute("user");
		Map<String, Object> mapJson = new HashMap<String, Object>();
		for (RolePo role : userPo.getRoleBeans()) {
			if(roleIds.indexOf(""+role.getRoleId()) >= 0){
				mapJson.put("result", "删除失败");
				mapJson.put("type", 0);
				mapJson.put("message", "存在正在使用中的角色！");
				out.print(JsonUtil.objectToStr(mapJson));
				out.flush();
				out.close();
				return NONE;
			}
		}
		
		List<RolePo> rolePoList = new ArrayList<RolePo>();
		String [] ids = roleIds.split(",");
		for (int i = 0; i < ids.length; i++) {
			if("1".equals(ids[i])){
				mapJson.put("result", "删除失败");
				mapJson.put("type", 0);
				mapJson.put("message", "您删除的角色存在超级管理员！");
				out.print(JsonUtil.objectToStr(mapJson));
				out.flush();
				out.close();
				return NONE;
			}
			RolePo role = new RolePo();
			role = roleService.getRoleByRoleId(new Integer(ids[i]));
			role.setIsDelete(1);
			role.setUserBeans(null);
			role.setTreeMenuPos(null);
			rolePoList.add(role);
		}
		
		//String sql = "UPDATE RolePo set isdelete = 1 WHERE roleId IN (" + roleIds + ")";
		//roleService.executeUpdates(sql);
		int total = roleService.deleteRoleList(rolePoList);
		mapJson.put("result", "删除成功");
		mapJson.put("type", 1);
		mapJson.put("message", total + "个角色被删除成功！");
		out.print(JsonUtil.objectToStr(mapJson));
		out.flush();
		out.close();
		return NONE;
	}
	
	public String execute() throws Exception {
		// TODO Auto-generated method stub
		return null;
	}


}
